<template>
  <a-spin :spinning="confirmLoading">
    <!--查询区域-->
    <div class="jeecg-basic-table-form-container">
      <a-form @keyup.enter.native="searchQuery" :model="queryParam" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-row :gutter="24">
          <a-col :lg="6">
            <a-form-item label="签约商户">
              <j-search-select placeholder="请选择签约商户" v-model:value="queryParam.businessId" dict="caishui_business,name,id,type=1 and is_default=0" />
            </a-form-item>
          </a-col>
          <a-col :lg="6">
            <a-form-item label="服务公司">
              <j-search-select placeholder="请选择服务公司" v-model:value="queryParam.companyId" dict="caishui_middle_company,company_name,company_id" />
            </a-form-item>
          </a-col>
          <a-col :lg="6">
            <a-form-item label="退款状态">
              <j-dict-select-tag placeholder="请选择退款状态" v-model:value="queryParam.status" dictCode="refund_record_status"/>
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :lg="6">
              <a-form-item label="业务参考号">
                <a-input placeholder="请输入业务参考号" v-model:value="queryParam.yurRef"></a-input>
              </a-form-item>
            </a-col>
            <a-col :lg="6">
              <a-form-item label="收方账号">
                <a-input placeholder="请输入收方账号" v-model:value="queryParam.crtAccount"></a-input>
              </a-form-item>
            </a-col>
            <a-col :lg="6">
              <a-form-item label="收方户名">
                <a-input placeholder="请输入收方户名" v-model:value="queryParam.crtName"></a-input>
              </a-form-item>
            </a-col>
            <a-col :lg="12">
              <a-form-item label="创建时间">
                <a-date-picker showTime value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择开始时间" v-model:value="queryParam.createTime_begin" class="query-group-cust" />
                <span class="query-group-split-cust">~</span>
                <a-date-picker showTime value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择结束时间" v-model:value="queryParam.createTime_end" class="query-group-cust" />
              </a-form-item>
            </a-col>
            <a-col :lg="12">
              <a-form-item label="提交时间">
                <a-date-picker showTime value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择开始时间" v-model:value="queryParam.submitTime_begin" class="query-group-cust" />
                <span class="query-group-split-cust">~</span>
                <a-date-picker showTime value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择结束时间" v-model:value="queryParam.submitTime_end" class="query-group-cust" />
              </a-form-item>
            </a-col>
            <a-col :lg="12">
              <a-form-item label="审核时间">
                 <a-date-picker showTime value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择开始时间" v-model:value="queryParam.checkTime_begin" class="query-group-cust" />
                 <span class="query-group-split-cust">~</span>
                 <a-date-picker showTime value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择结束时间" v-model:value="queryParam.checkTime_end" class="query-group-cust" />
              </a-form-item>
            </a-col>
            <a-col :lg="12">
              <a-form-item label="银行处理时间">
                 <a-date-picker showTime value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择开始时间" v-model:value="queryParam.finishTime_begin" class="query-group-cust" />
                 <span class="query-group-split-cust">~</span>
                 <a-date-picker showTime value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择结束时间" v-model:value="queryParam.finishTime_end" class="query-group-cust" />
              </a-form-item>
            </a-col>
          </template>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-col :lg="6">
                <a-button type="primary" preIcon="ant-design:search-outlined" @click="searchQuery">查询</a-button>
                <a-button type="primary" preIcon="ant-design:reload-outlined" @click="searchReset" style="margin-left: 8px">重置</a-button>
                <a @click="toggleSearchStatus = !toggleSearchStatus" style="margin-left: 8px">
                  {{ toggleSearchStatus ? '收起' : '展开' }}
                  <Icon :icon="toggleSearchStatus ? 'ant-design:up-outlined' : 'ant-design:down-outlined'" />
                </a>
              </a-col>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!--引用表格-->
    <BasicTable @register="registerTable" :columns="tableColumns">
      <!--插槽:table标题-->
      <template #tableTitle>
        <div>
          <a-radio-group v-model:value="activeKey" button-style="solid" @change="handleRadioChange">
            <a-radio-button value="1">　审核中　</a-radio-button>
            <a-radio-button value="2">　审核驳回　</a-radio-button>
            <a-radio-button value="3">　银行处理中　</a-radio-button>
            <a-radio-button value="4">　退款成功　</a-radio-button>
            <a-radio-button value="5">　退款失败　</a-radio-button>
          </a-radio-group>
        </div>
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)"/>
      </template>
      <!--付方信息插槽-->
      <template #paySlot="{record}">
        <span style="text-align: left;">
          <p>付方户名：<span >{{record.payName}}</span></p>
          <p>付方账号：<span >{{record.payAccount}}{{record.payDmanbr}}</span></p>
          <p>付方公司：<span >{{record.payDmanam}}</span></p>
        </span>
      </template>
      <!--收方信息插槽-->
      <template #artSlot="{record}">
        <span style="text-align: left;">
          <p>收方户名：<span >{{record.crtName}}</span></p>
          <p>收方账号：<span >{{record.crtAccount}}</span></p>
          <p>开户银行：<span >{{record.bankName}}</span></p>
          <p>开户支行：<span >{{record.bankBranch}}</span></p>
<!--          <p>开户地：<span >{{record.bankAddress}}</span></p>-->
        </span>
      </template>
      <!--退款金额插槽-->
      <template #moneySlot="{record}">
        <span style="text-align: left;">
          <p>退款金额：<span style="font-weight: bold;">{{parseFloat(record.money).toFixed(2)}}</span></p>
          <p>服务费：<span>{{parseFloat(record.serviceFee).toFixed(2)}}</span></p>
          <p>实际到账金额：<span style="font-weight: bold;">{{parseFloat(record.money-record.serviceFee).toFixed(2)}}</span></p>
        </span>
      </template>
      <!--银行处理结果插槽-->
      <template #reqSlot="{record}">
        <p v-if="!record.reqSts_dictText && !record.rtnFlg_dictText">-</p>
        <span style="text-align: left;">
          <p v-if="record.reqSts_dictText">请求状态：<span >{{record.reqSts_dictText}}</span></p>
          <p v-if="record.rtnFlg_dictText">业务处理结果：<span >{{record.rtnFlg_dictText}}</span></p>
          <p v-if="record.failReason">处理失败原因：<span >{{record.failReason}}</span></p>
        </span>
      </template>
      <!--退款状态插槽-->
      <template #statusSlot="{record}">
        <a-badge v-if="record.status==-1" color="grey" :text="record.status_dictText" />
        <a-badge v-if="record.status==0" color="cyan" :text="record.status_dictText" />
        <a-badge v-if="record.status==1" color="orange" :text="record.status_dictText" />
        <a-badge v-if="record.status==2" color="purple" :text="record.status_dictText" />
        <a-badge v-if="record.status==3" color="blue" :text="record.status_dictText" />
        <a-badge v-if="record.status==4" color="green" :text="record.status_dictText" />
        <a-badge v-if="record.status==5" color="red" :text="record.status_dictText" />
        <p v-if="record.status==2">驳回理由：<span >{{record.rejectReason}}</span></p>
      </template>
    </BasicTable>
    <!-- 驳回弹框区域 -->
    <RejectReasonForm ref="registerRejectReasonForm" @success="rejectReasonSuccess"></RejectReasonForm>
    <!-- 验证手机区域 -->
    <VerifyPhone ref="registerVerifyPhone" @success="handleVerifyPhoneSuccess"></VerifyPhone>
  </a-spin>
</template>

<script lang="ts" name="caishuiRefundRecord-caishuiRefundRecord" setup>
  import { ref, reactive } from 'vue';
  import { BasicTable, TableAction } from '/@/components/Table';
  import { useListPage } from '/@/hooks/system/useListPage';
  import { columns, columns1, columns2 } from './CaishuiRefundRecord.data';
  import { list, statusOne, getExportUrl, queryByYurRef } from './CaishuiRefundRecord.api';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import JSearchSelect from '/@/components/Form/src/jeecg/components/JSearchSelect.vue';
  import { useMessage } from "/@/hooks/web/useMessage";
  import RejectReasonForm from "/@/views/auditCenter/common/RejectReasonForm.vue";
  import VerifyPhone from "/@/layouts/default/header/components/user-dropdown/VerifyPhone.vue";

  const queryParam = ref<any>({});
  const toggleSearchStatus = ref<boolean>(false);
  const registerModal = ref();
  const exportIconLoading = ref<boolean>(false);
  const confirmLoading = ref<boolean>(false);
  const { createMessage } = useMessage();
  const tableColumns = ref<any>(columns);
  const activeKey = ref('1');
  const btnLoading = ref<boolean>(false);
  const registerRejectReasonForm = ref();
  const registerVerifyPhone = ref();
  //注册table数据
  const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
    tableProps: {
      title: '退款记录',
      api: list,
      canResize:false,
      useSearchForm: false,
      striped: true,
      showIndexColumn: true,
      ellipsis: false,
      actionColumn: {
        width: 150,
        fixed: 'right',
      },
      beforeFetch: (params) => {
        params.status = activeKey.value;
        return Object.assign(params, queryParam.value);
      },
    },
    exportConfig: {
      name: "退款记录",
      url: getExportUrl,
      success: exportXlsSuccess
    },
  });
  const [registerTable, { reload, collapseAll, updateTableDataRecord, findTableDataRecord, getDataSource }, { rowSelection, selectedRowKeys }] = tableContext;
  const labelCol = reactive({
    xs: { span: 24 },
    sm: { span: 6 },
  });
  const wrapperCol = reactive({
    xs: { span: 24 },
    sm: { span: 16 },
  });

  /**
   * 改变单选框事件
   * @param e
   */
  function handleRadioChange(e){
    if(activeKey.value==='1'){
      tableColumns.value = columns;
    }else if(activeKey.value==='2' || activeKey.value==='3'){
      tableColumns.value = columns.concat(...columns1);
    }else if(activeKey.value==='4' || activeKey.value==='5'){
      tableColumns.value = columns.concat(...columns1,...columns2);
    };
    searchQuery();//查询
  }

  /**
   * 审核事件
   * @param status
   */
  function handleConfirm(id,status){
    registerVerifyPhone.value.show(id,status);
  }
  /**
   * 验证手机完成之后提交事件
   */
  function handleVerifyPhoneSuccess(data) {
    handleCheck(data.id, data.status, data.rejectReason,data.captcha);
  }

  /**
   * 驳回弹窗事件
   */
  function handleEdit(record: Recordable) {
    registerRejectReasonForm.value.show(record.id, 2);
  }
  function rejectReasonSuccess(data){
    handleCheck(data.id, data.status, data.rejectReason,"");
  }

  /**
   * 审核事件
   * @param id
   * @param status
   * @param rejectReason
   */
  async function handleCheck(id,status,rejectReason,captcha) {
    btnLoading.value = true;
    await statusOne({ id: id, status: status, rejectReason: rejectReason,captcha: captcha }).then((res) => {
      if (res.success) {
        createMessage.success(res.message);
      } else {
        createMessage.warning(res.message);
      }
    }).finally(() => {
      btnLoading.value = false;
      handleSuccess();
    });
  }

  /**
   * 查询退款结果
   * @param yurRef
   */
  function queryResult(yurRef){
    btnLoading.value = true;
    queryByYurRef({ yurRef: yurRef }).then((res) => {
      if (res.success) {
        createMessage.success(res.message);
        handleSuccess();
      } else {
        createMessage.warning(res.message);
      }
    }).finally(() => {
      btnLoading.value = false;
    });
  }

  /**
   * 成功回调
   */
  function handleSuccess() {
    (selectedRowKeys.value = []) && reload();
  }
   
  /**
   * 操作栏
   */
  function getTableAction(record) {
    return [
      {
        label: '通过',
        ifShow: record.status==1,
        loading: btnLoading,
        icon: 'ant-design:check-outlined',
        popConfirm: {
          title: '是否确认审核通过？',
          confirm: handleConfirm.bind(null, record.id,3),
        }
      },
      {
        label: '驳回',
        ifShow: record.status==1,
        loading: btnLoading,
        icon: 'ant-design:close-outlined',
        onClick: handleEdit.bind(null, record),
      },
      {
        label: '查询结果',
        ifShow: record.status==3,
        loading: btnLoading,
        icon: 'ant-design:search-outlined',
        onClick: queryResult.bind(null, record.yurRef),
      },
    ];
  }

  /**
   * 查询
   */
  function searchQuery() {
    reload();
  }
  
  /**
   * 重置
   */
  function searchReset() {
    queryParam.value = {};
    selectedRowKeys.value = [];
    //刷新数据
    reload();
  }

  /**
   * 导出
   */
  function handleExportXls() {
    exportIconLoading.value = true;
    onExportXls();
  }

  /**
   * 导出成功回调
   */
  function exportXlsSuccess(data) {
    exportIconLoading.value = false;
  }

</script>

<style lang="less" scoped>
  .jeecg-basic-table-form-container {
    .table-page-search-submitButtons {
      display: block;
      margin-bottom: 24px;
      white-space: nowrap;
    }
    .query-group-cust{
      width: calc(50% - 15px);
      min-width: 100px !important;
    }
    .query-group-split-cust{
      width: 30px;
      display: inline-block;
      text-align: center
    }
  }
</style>
